package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = ((CreateOrderContext) context);

        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        if (CollectionUtils.isEmpty(buyProductIds)) {
            buyProductIds = new LinkedList<>();
            for (CartProductDto cartProductDto : dtoList) {
                buyProductIds.add(cartProductDto.getProductId());
            }
            buyProductIds.sort(Long::compareTo);
            List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(buyProductIds);
            // 库存锁定判断如果库存为空
            if (CollectionUtils.isEmpty(stocksForUpdate)) {
                throw new BizException("库存未初始化");
            }

            // 部分商品库存未初始化
            if (stocksForUpdate.size() != buyProductIds.size()) {
                throw new BizException("部分商品库存未初始化");
            }

            // 库存扣减
            for (CartProductDto cartProductDto : dtoList) {
                Long productId = cartProductDto.getProductId();
                Long productNum = cartProductDto.getProductNum();

                // productNum不能超出限购数量
                Stock stockTemp = stockMapper.selectStock(productId);
                if (productNum > stockTemp.getRestrictCount()) {
                    throw new BizException("超出限购数量");
                }

                Stock stock = new Stock();
                stock.setItemId(productId);
                stock.setLockCount(productNum.intValue());
                stock.setStockCount(-productNum);
                stockMapper.updateStock(stock);
            }
        }
        return true;
    }
}